package auto.app.util;

import auto.app.controller.info.LoginAccountInfo;
import auto.app.dao.ResourceDao;
import auto.app.model.Resource;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private ResourceDao ResourceDao;

    @Autowired
    private RedisTemplate redisTemplate;

    private ObjectMapper objectMapper=new ObjectMapper();
    private final static String redisResources="resources:accountid:%s";

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setCharacterEncoding("utf-8");
        LoginAccountInfo loginAccountInfo=new LoginAccountInfo();
        BeanUtils.copyProperties(authentication.getPrincipal(),loginAccountInfo);
        //根据uid查询出角色的权限
        List<Resource> resourceList = ResourceDao.findResourceByAccountId(loginAccountInfo.getAccountId());
        ArrayList<String> stringArrayList=new ArrayList<>();
        for (Resource resource : resourceList) {
            stringArrayList.add(resource.getResourceUri());
        }
        //将权限存入redis中
        redisTemplate.opsForValue().set(String.format(redisResources,loginAccountInfo.getAccountId()),stringArrayList);
        //用户权限存入token中
//        httpServletRequest.getSession().setAttribute("resources",stringArrayList);
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("accountid",loginAccountInfo.getAccountId());
        hashMap.put("userName",loginAccountInfo.getAccountName());
        String jwt = JwtTemplate.createJwt(3600, hashMap);
        loginAccountInfo.setToken(jwt);
//        httpServletRequest.getSession().setAttribute("accountid",loginAccountInfo.getAccountId());
//        httpServletRequest.getSession().setAttribute("userName",loginAccountInfo.getAccountName());
        //写出返回值
        Result<LoginAccountInfo> result = Result.getInstance(LoginAccountInfo.class).setCode(200).setMsg("登陆成功").setData(loginAccountInfo);
        String s = objectMapper.writeValueAsString(result);
        httpServletResponse.getWriter().write(s);
        httpServletResponse.getWriter().flush();
    }
}
